package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import cn.eeepay.api.grpc.nano.PersonProto;
import cn.eeepay.api.grpc.nano.PersonApiServiceGrpc;
import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.PersonInfo;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.BaseGrpcTask;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ABRegUtil;
import com.eeepay.v2_library.view.HorizontalItemView;
import com.eeepay.v2_library.view.LabelEditText;
import com.eeepay.v2_library.view.TitleBar;
import com.google.protobuf.Type;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/15 0015.
 * 人员编辑页面      人员添加页面
 */
public class PersonEditActivity extends ABBaseActivity implements View.OnClickListener {

    private TitleBar titleBar;
    private LabelEditText et_name, et_phone, et_email;//姓名电话
    private HorizontalItemView hv_role, hv_state;//角色、状态
    private Button btn_confirm;

    private String id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person_edit;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.title_bar);
        et_name = getViewById(R.id.et_name);
        et_phone = getViewById(R.id.et_phone);
        et_email = getViewById(R.id.et_email);
        et_phone.getEditText().setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        et_phone.getEditText().setInputType(Type.FIELDS_FIELD_NUMBER);
        hv_role = getViewById(R.id.hv_role);
        hv_state = getViewById(R.id.hv_state);

        PersonInfo person = (PersonInfo) bundle.getSerializable("personInfo");
        if(person != null){
            id = person.getId();
            et_name.getEditText().setText(person.getName());
            et_phone.getEditText().setText(person.getPhone());
            hv_role.setRightText(person.getRole());
            hv_state.setRightText(person.getState());
            et_email.getEditText().setText(person.getEmail());
        }

        btn_confirm = getViewById(R.id.btn_confirm);

        et_phone.getEditText().setFocusableInTouchMode(false);
        et_email.getEditText().setFocusableInTouchMode(false);
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        new GrpcTask().execute(Constant.URL.URL, Constant.URL.PORT);
    }

    @Override
    protected void eventOnClick() {
        hv_role.setOnClickListener(this);
        hv_state.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.hv_role:
                Bundle bundle = new Bundle();
                bundle.putString(Constant.INTENT_FLAG, Constant.PERSON_ROLE);
                goActivityForResult(ChooseActivity.class, bundle, Constant.RequestCode.person_role);
                break;
            case R.id.hv_state:
                Bundle bundle2 = new Bundle();
                bundle2.putString(Constant.INTENT_FLAG, Constant.PERSON_STATUS);
                goActivityForResult(ChooseActivity.class, bundle2, Constant.RequestCode.person_statu);
                break;
            case R.id.btn_confirm:
                updatePerson();
                break;
        }
    }

    /**
     * 判断输入条件
     */
    private void updatePerson() {
        if(TextUtils.isEmpty(et_name.getEditContent())){
            Toast.makeText(mContext, "请输入姓名", Toast.LENGTH_SHORT).show();
            return;
        }
        if(!ABRegUtil.isRegiest(et_phone.getEditContent(), ABRegUtil.REG_PHONE_CHINA)){
            Toast.makeText(mContext, "请输入正确手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(!ABRegUtil.isRegiest(et_email.getEditContent(), ABRegUtil.REG_EMAIL)){
            Toast.makeText(mContext, "请输入正确邮箱", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(hv_role.getRightText()) || "请选择".equals(hv_role.getRightText())){
            Toast.makeText(mContext, "请选择人员角色", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(hv_state.getRightText())|| "请选择".equals(hv_state.getRightText())){
            Toast.makeText(mContext, "请选择人员状态", Toast.LENGTH_SHORT).show();
            return;
        }
        if(!ABRegUtil.isRegiest(et_phone.getEditContent(), ABRegUtil.REG_PHONE_CHINA)){
            Toast.makeText(mContext, "不是正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        sendHttpRequest(0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != RESULT_OK){
            return;
        }
        switch (requestCode){
            case Constant.RequestCode.person_role:
                if(data != null){
                    hv_role.setRightText(data.getStringExtra(Constant.PERSON_ROLE));
                }
                break;
            case Constant.RequestCode.person_statu:
                if(data != null){
                    hv_state.setRightText(data.getStringExtra(Constant.PERSON_STATUS));
                }
                break;
        }
    }

    private class GrpcTask extends BaseGrpcTask<PersonProto.ResultMsgResponse> {

        @Override
        protected PersonProto.ResultMsgResponse doInBack(ManagedChannel channel) {
            PersonApiServiceGrpc.PersonApiServiceBlockingStub stub = PersonApiServiceGrpc
                    .newBlockingStub(channel)
                    .withDeadlineAfter(5, TimeUnit.SECONDS);
            PersonProto.PersonRequest request = new PersonProto.PersonRequest();
            request.userId = id;
            LogUtils.d(Constant.TAG, "id = " + id);
            request.agentNo = UserInfo.getUserInfo2SP().getAgentNo();
            request.teamId = ConfigPorperties.getInstance().getTeamId();
            request.name = et_name.getEditText().getText().toString().trim();
            request.manage = "管理员".equals(hv_role.getRightText()) ? "1": "0";
            request.status = "正常".equals(hv_state.getRightText()) ? "1": "0";
            request.mobilephone = et_phone.getEditText().getText().toString().trim();
            request.email = et_email.getEditContent();
            PersonProto.ResultMsgResponse response = stub.updatePersonInfoRpc(request);
            return response;
        }

        @Override
        protected void updateUI(PersonProto.ResultMsgResponse result) {
            dismissProgressDialog();
            if(result == null){
                Toast.makeText(mContext, "修改失败" , Toast.LENGTH_SHORT).show();
                return;
            }
            String code = result.code;
            LogUtils.d(Constant.TAG, "codeInfo = " + result.codeInfo);
            if("false".equals(code)){

                Toast.makeText(mContext, result.codeInfo , Toast.LENGTH_SHORT).show();
                return;
            }else{
                Toast.makeText(mContext, "修改成功" , Toast.LENGTH_SHORT).show();
            }

            finish();
        }
    }
}
